import 'package:flutter/material.dart';
import '../models/user.dart';
import '../models/pet.dart';
import '../models/video.dart';
import '../models/post.dart';
import '../api/api_service.dart';

class AppState with ChangeNotifier {
  final ApiService _apiService = ApiService();
  
  // 用户信息
  User? _currentUser;
  bool _isLoggedIn = false;
  bool _isLoading = false;
  
  // 收藏和点赞数据
  Set<int> _likedVideos = {};
  Set<int> _likedPosts = {};
  Set<int> _favoriteVideos = {};
  Set<int> _favoritePets = {};
  
  // 缓存数据
  List<Pet> _petCache = [];
  List<Video> _videoCache = [];
  List<Post> _postCache = [];

  // 用户收藏的宠物ID
  List<String> _favoritePets = [];
  // 用户收藏的帖子ID
  List<String> _favoritePosts = [];
  // 用户收藏的视频ID
  List<String> _favoriteVideos = [];
  
  // 用户最近浏览的宠物ID
  List<String> _recentlyViewedPets = [];
  // 用户最近浏览的帖子ID
  List<String> _recentlyViewedPosts = [];
  // 用户最近浏览的视频ID
  List<String> _recentlyViewedVideos = [];
  
  // 是否是深色模式
  bool _isDarkMode = false;
  
  // 未读通知数量
  int _unreadNotifications = 0;

  // Getters
  User? get currentUser => _currentUser;
  bool get isLoggedIn => _isLoggedIn;
  bool get isLoading => _isLoading;
  Set<int> get likedVideos => _likedVideos;
  Set<int> get likedPosts => _likedPosts;
  Set<int> get favoriteVideos => _favoriteVideos;
  Set<int> get favoritePets => _favoritePets;
  
  List<String> get favoritePosts => _favoritePosts;
  List<String> get favoriteVideos => _favoriteVideos;
  
  List<String> get recentlyViewedPets => _recentlyViewedPets;
  List<String> get recentlyViewedPosts => _recentlyViewedPosts;
  List<String> get recentlyViewedVideos => _recentlyViewedVideos;
  
  bool get isDarkMode => _isDarkMode;
  
  int get unreadNotifications => _unreadNotifications;
  
  // 初始化应用状态
  Future<void> initialize() async {
    _setLoading(true);
    try {
      // 模拟加载当前用户（使用ID为1的用户）
      _currentUser = await _apiService.getUser(1);
      _isLoggedIn = true;
      
      // 预加载部分数据
      _petCache = await _apiService.getPets(limit: 10);
      _videoCache = await _apiService.getVideos(limit: 10);
      _postCache = await _apiService.getPosts(limit: 10);
      
      _setLoading(false);
    } catch (e) {
      _setLoading(false);
      print('初始化应用状态失败: $e');
    }
  }
  
  // 登录
  Future<bool> login(String username, String password) async {
    _setLoading(true);
    try {
      // 模拟登录逻辑
      await Future.delayed(Duration(seconds: 1));
      _currentUser = await _apiService.getUser(1);
      _isLoggedIn = true;
      _setLoading(false);
      notifyListeners();
      return true;
    } catch (e) {
      _setLoading(false);
      print('登录失败: $e');
      return false;
    }
  }
  
  // 登出
  void logout() {
    _currentUser = null;
    _isLoggedIn = false;
    notifyListeners();
  }
  
  // 设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    notifyListeners();
  }
  
  // 点赞/取消点赞视频
  void toggleLikeVideo(int videoId) {
    if (_likedVideos.contains(videoId)) {
      _likedVideos.remove(videoId);
    } else {
      _likedVideos.add(videoId);
    }
    notifyListeners();
  }
  
  // 点赞/取消点赞帖子
  void toggleLikePost(int postId) {
    if (_likedPosts.contains(postId)) {
      _likedPosts.remove(postId);
    } else {
      _likedPosts.add(postId);
    }
    notifyListeners();
  }
  
  // 收藏/取消收藏视频
  void toggleFavoriteVideo(int videoId) {
    if (_favoriteVideos.contains(videoId)) {
      _favoriteVideos.remove(videoId);
    } else {
      _favoriteVideos.add(videoId);
    }
    notifyListeners();
  }
  
  // 收藏/取消收藏宠物
  void toggleFavoritePet(int petId) {
    if (_favoritePets.contains(petId)) {
      _favoritePets.remove(petId);
    } else {
      _favoritePets.add(petId);
    }
    notifyListeners();
  }
  
  // 发布新帖子 (模拟)
  Future<bool> createPost(String title, String content, List<String> images) async {
    _setLoading(true);
    try {
      // 模拟网络请求
      await Future.delayed(Duration(seconds: 1));
      
      // 创建一个新的帖子对象
      final newPost = Post(
        id: DateTime.now().millisecondsSinceEpoch,
        title: title,
        content: content,
        userId: _currentUser?.id ?? 1,
        postTime: DateTime.now(),
        images: images,
        likes: 0,
        comments: 0,
        userAvatar: _currentUser?.avatar ?? 'https://via.placeholder.com/150',
        username: _currentUser?.username ?? '用户',
      );
      
      // 添加到缓存
      _postCache.insert(0, newPost);
      
      _setLoading(false);
      notifyListeners();
      return true;
    } catch (e) {
      _setLoading(false);
      print('发布帖子失败: $e');
      return false;
    }
  }
  
  // 发布新宠物信息 (模拟)
  Future<bool> createPet(String name, String species, String breed, int age, String gender, String description, List<String> images, bool isForAdoption) async {
    _setLoading(true);
    try {
      // 模拟网络请求
      await Future.delayed(Duration(seconds: 1));
      
      // 创建一个新的宠物对象
      final newPet = Pet(
        id: DateTime.now().millisecondsSinceEpoch,
        name: name,
        species: species,
        breed: breed,
        age: age,
        gender: gender,
        description: description,
        images: images,
        ownerId: _currentUser?.id ?? 1,
        isForAdoption: isForAdoption,
        createdAt: DateTime.now(),
      );
      
      // 添加到缓存
      _petCache.insert(0, newPet);
      
      _setLoading(false);
      notifyListeners();
      return true;
    } catch (e) {
      _setLoading(false);
      print('发布宠物信息失败: $e');
      return false;
    }
  }

  void setCurrentUser(User user) {
    _currentUser = user;
    notifyListeners();
  }
  
  void setUnreadNotifications(int count) {
    _unreadNotifications = count;
    notifyListeners();
  }

  // 切换深色模式
  void toggleDarkMode() {
    _isDarkMode = !_isDarkMode;
    notifyListeners();
  }

  // 切换宠物收藏状态
  void toggleFavoritePet(String petId) {
    if (_favoritePets.contains(petId)) {
      _favoritePets.remove(petId);
    } else {
      _favoritePets.add(petId);
    }
    notifyListeners();
  }

  // 切换帖子收藏状态
  void toggleFavoritePost(String postId) {
    if (_favoritePosts.contains(postId)) {
      _favoritePosts.remove(postId);
    } else {
      _favoritePosts.add(postId);
    }
    notifyListeners();
  }

  // 切换视频收藏状态
  void toggleFavoriteVideo(String videoId) {
    if (_favoriteVideos.contains(videoId)) {
      _favoriteVideos.remove(videoId);
    } else {
      _favoriteVideos.add(videoId);
    }
    notifyListeners();
  }

  // 添加最近浏览的宠物
  void addViewedPet(String petId) {
    // 如果已经存在，先移除旧的记录
    _recentlyViewedPets.remove(petId);
    // 添加到列表开头
    _recentlyViewedPets.insert(0, petId);
    // 限制列表长度为50
    if (_recentlyViewedPets.length > 50) {
      _recentlyViewedPets = _recentlyViewedPets.sublist(0, 50);
    }
    notifyListeners();
  }

  // 添加最近浏览的帖子
  void addViewedPost(String postId) {
    _recentlyViewedPosts.remove(postId);
    _recentlyViewedPosts.insert(0, postId);
    if (_recentlyViewedPosts.length > 50) {
      _recentlyViewedPosts = _recentlyViewedPosts.sublist(0, 50);
    }
    notifyListeners();
  }

  // 添加最近浏览的视频
  void addViewedVideo(String videoId) {
    _recentlyViewedVideos.remove(videoId);
    _recentlyViewedVideos.insert(0, videoId);
    if (_recentlyViewedVideos.length > 50) {
      _recentlyViewedVideos = _recentlyViewedVideos.sublist(0, 50);
    }
    notifyListeners();
  }
  
  // 关注用户
  void followUser(String userId) {
    if (_currentUser != null) {
      _currentUser = _currentUser!.follow(userId);
      notifyListeners();
    }
  }
  
  // 取消关注用户
  void unfollowUser(String userId) {
    if (_currentUser != null) {
      _currentUser = _currentUser!.unfollow(userId);
      notifyListeners();
    }
  }
  
  // 切换关注状态
  void toggleFollowUser(String userId) {
    if (_currentUser != null) {
      if (_currentUser!.isFollowing(userId)) {
        unfollowUser(userId);
      } else {
        followUser(userId);
      }
    }
  }
  
  // 检查是否关注了某用户
  bool isFollowing(String userId) {
    return _currentUser?.isFollowing(userId) ?? false;
  }
} 